package cn.xfdzx.android.apps.shop.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.example.caller.BankABCCaller;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.NewOrderBeen;
import cn.xfdzx.android.apps.shop.contract.PayContract;
import cn.xfdzx.android.apps.shop.evenbus.CarInitDataMessage;
import cn.xfdzx.android.apps.shop.evenbus.HomeFlushCarData;
import cn.xfdzx.android.apps.shop.evenbus.OrderMoneyMessage;
import cn.xfdzx.android.apps.shop.presenter.OrderPayPresenter;
import cn.xfdzx.android.apps.shop.util.PayResult;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import static cn.xfdzx.android.apps.shop.apps.Constants.WX_APP_ID;

/**
 * 支付收银台
 */
public class PaymentDeskOrderActivity extends BaseMvpActivity<OrderPayPresenter> implements PayContract.View {

    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.bt_pay)
    Button btPay;
    @BindView(R.id.tv_remaining_time)
    TextView tvRemainingTime;
    @BindView(R.id.iv_select_zhifubao)
    ImageView ivSelectZhifubao;
    @BindView(R.id.iv_select_weixin)
    ImageView ivSelectWeixin;
    @BindView(R.id.iv_select_nonghang)
    ImageView ivSelectNonghang;

    private String delivery_method = "";
    private RelativeLayout.LayoutParams item_bar;
    private IWXAPI api;
    private String orderKey = "";
    private String address_id = "";
    private String order_express_type = ""; //'1-今日2-明日3-后日'
    private String logistics_type = "";
    private String from = "";
    private String pay_type = "weixin";
    private String leftName;
    private String rightName;
    private String marks;
    private static final int SDK_PAY_FLAG = 1;
    private Context mContext;

    @Override
    public int getLayoutId() {
        return R.layout.activity_payment_desk_order;
    }

    @Override
    public void initView() {
        mContext = PaymentDeskOrderActivity.this;
        initHigh();
        mPresenter = new OrderPayPresenter();
        mPresenter.attachView(this);
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID);
        from = getIntent().getStringExtra("from");
        if (from.equals("submit")) {
            tvTotalMoney.setText("¥ " + getIntent().getStringExtra("totalMoney"));
            orderKey = getIntent().getStringExtra("orderKey");
            address_id = getIntent().getStringExtra("address_id");
            order_express_type = getIntent().getStringExtra("order_express_type");
            rightName = getIntent().getStringExtra("rightName");
            logistics_type = getIntent().getStringExtra("logistics_type");
            marks = getIntent().getStringExtra("marks");
            delivery_method = getIntent().getStringExtra("delivery_method");
        } else if (from.equals("routine")) {
            tvTotalMoney.setText("¥ " + getIntent().getStringExtra("totalMoney"));
            orderKey = getIntent().getStringExtra("orderKey");

        }

    }

    @Override
    public void showLoading() {
        ProgressDialog.getInstance().show(this);
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {
//        Utils.toastMessage(this,throwable.toString());
        Log.e("onError", throwable.toString());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);

    }

    @Override
    protected void onResume() {
        super.onResume();
        String param = getIntent().getStringExtra("from_bankabc_param");
        if (param != null) {
            param = param.substring(param.indexOf("STT="), param.length());
            String result = param.substring(4, param.indexOf("&"));
            Log.e("支付结果", "param===" + result);
            if ("0000".equals(result)) {
                //支付成功
                intent = new Intent(this, MainActivity.class);
                intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
                intent.putExtra("from", "pay");
                startActivity(intent);
                return;
            } else if ("9999".equals(result)) {
                Utils.toastMessage(this, "支付未完成");


            } else if ("PA500401".equals(result)) {
                Utils.toastMessage(this, "已存在成功支付的订单");
            } else {
                Utils.toastMessage(this, "支付出错");
            }
            intent = new Intent(this, MainActivity.class);
            intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
            intent.putExtra("from", "pay_cancel");
            startActivity(intent);
        }
    }

    @Override
    public void onConfirmOrderSuccess(NewOrderBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            //刷新购物车批发列表
            EventBus.getDefault().post(new CarInitDataMessage(1));
            EventBus.getDefault().post(new HomeFlushCarData());
            if (pay_type.equals("weixin")) {
                boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
                if (isPaySupported) {
                    PayReq req = new PayReq();
                    req.appId = bean.getData().getResult().getJsConfig().getAppid();
                    req.partnerId = bean.getData().getResult().getJsConfig().getPartnerid();
                    req.prepayId = bean.getData().getResult().getJsConfig().getPrepayid();
                    req.nonceStr = bean.getData().getResult().getJsConfig().getNoncestr();
                    req.timeStamp = bean.getData().getResult().getJsConfig().getTimestamp() + "";
                    req.packageValue = bean.getData().getResult().getJsConfig().getPackageX();
                    req.sign = bean.getData().getResult().getJsConfig().getSign();
                    req.extData = "";
                    api.sendReq(req);
                } else {
                    Toast.makeText(this, "当前微信版本不支持支付", Toast.LENGTH_SHORT).show();
                }
            } else if (pay_type.equals("alipay")) {
                final Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PaymentDeskOrderActivity.this);
                        Map<String, String> result = alipay.payV2(bean.getData().getResult().getAlipay_param(), true);
                        Log.i("msp", result.toString());

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else if (pay_type.equals("abcp")) {
/**
 * 判断手机上是否具备调起农行掌银的条件
 */
                if (BankABCCaller.isBankABCAvaiable(PaymentDeskOrderActivity.this)) {

                    /**
                     * 调起农行掌银
                     */
//                    BankABCCaller.startBankABC(ConfirmOrderActivity.this, "cn.xfdzx.android.apps.shop", "cn.xfdzx.android.apps.shop.activity.ConfirmOrderActivity", "pay", bean.getData().getResult().getAbcApp());
                    BankABCCaller.startBankABC(PaymentDeskOrderActivity.this, "cn.xfdzx.android.apps.shop", "cn.xfdzx.android.apps.shop.activity.PaymentDeskOrderActivity", "pay", bean.getData().getResult().getAbcApp());
                } else {//客户手机未安装农行掌银APP的处理逻辑，由第三方APP自行实现
                    Toast.makeText(PaymentDeskOrderActivity.this, "没安装农行掌银，或已安装农行掌银版本不支持", Toast.LENGTH_LONG).show();
                }
                return;

            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    public void onPaySuccess(NewOrderBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (pay_type.equals("weixin")) {
                boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
                if (isPaySupported) {
                    PayReq req = new PayReq();
                    req.appId = bean.getData().getResult().getJsConfig().getAppid();
                    req.partnerId = bean.getData().getResult().getJsConfig().getPartnerid();
                    req.prepayId = bean.getData().getResult().getJsConfig().getPrepayid();
                    req.nonceStr = bean.getData().getResult().getJsConfig().getNoncestr();
                    req.timeStamp = bean.getData().getResult().getJsConfig().getTimestamp() + "";
                    req.packageValue = bean.getData().getResult().getJsConfig().getPackageX();
                    req.sign = bean.getData().getResult().getJsConfig().getSign();
                    req.extData = "";
                    api.sendReq(req);
                } else {
                    Toast.makeText(this, "当前微信版本不支持支付", Toast.LENGTH_SHORT).show();
                }
            } else if (pay_type.equals("alipay")) {
                final Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PaymentDeskOrderActivity.this);
                        Map<String, String> result = alipay.payV2(bean.getData().getResult().getAlipay_param(), true);
                        Log.i("msp", result.toString());

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else if (pay_type.equals("abcp")) {
/**
 * 判断手机上是否具备调起农行掌银的条件
 */
                if (BankABCCaller.isBankABCAvaiable(PaymentDeskOrderActivity.this)) {

                    /**
                     * 调起农行掌银
                     */
//                    BankABCCaller.startBankABC(ConfirmOrderActivity.this, "cn.xfdzx.android.apps.shop", "cn.xfdzx.android.apps.shop.activity.ConfirmOrderActivity", "pay", bean.getData().getResult().getAbcApp());
                    BankABCCaller.startBankABC(PaymentDeskOrderActivity.this, "cn.xfdzx.android.apps.shop", "cn.xfdzx.android.apps.shop.activity.PaymentDeskOrderActivity", "pay", bean.getData().getResult().getAbcApp());
                } else {//客户手机未安装农行掌银APP的处理逻辑，由第三方APP自行实现
                    Toast.makeText(PaymentDeskOrderActivity.this, "没安装农行掌银，或已安装农行掌银版本不支持", Toast.LENGTH_LONG).show();
                }
                return;

            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @OnClick({R.id.iv_back, R.id.bt_pay, R.id.ll_weixin_pay, R.id.ll_zhifubao_pay, R.id.ll_nonghang_pay})
    public void Onclick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_weixin_pay:
                if (Utils.isFastClick()) {
                    pay_type = "weixin";
                    ivSelectWeixin.setImageResource(R.drawable.icon_green_dui);
                    ivSelectZhifubao.setImageResource(R.drawable.d99999_oval);
                    ivSelectNonghang.setImageResource(R.drawable.d99999_oval);
                }
                break;
            case R.id.ll_zhifubao_pay:
                if (Utils.isFastClick()) {
                    pay_type = "alipay";
                    ivSelectWeixin.setImageResource(R.drawable.d99999_oval);
                    ivSelectZhifubao.setImageResource(R.drawable.icon_green_dui);
                    ivSelectNonghang.setImageResource(R.drawable.d99999_oval);
                }
                break;
            case R.id.ll_nonghang_pay:
                if (Utils.isFastClick()) {
                    pay_type = "abcp";
                    ivSelectWeixin.setImageResource(R.drawable.d99999_oval);
                    ivSelectZhifubao.setImageResource(R.drawable.d99999_oval);
                    ivSelectNonghang.setImageResource(R.drawable.icon_green_dui);
                }
                break;
            case R.id.bt_pay:

                EventBus.getDefault().post(new OrderMoneyMessage(getIntent().getStringExtra("totalMoney"), "预计后天到达"));
                btPay.setEnabled(false);
                if (from.equals("submit")) {
                    if (order_express_type.equals("1")) {
                        leftName = "今日达";
                    } else if (order_express_type.equals("2")) {
                        leftName = "明日达";
                    } else if (order_express_type.equals("3")) {
                        leftName = "后日达";
                    }
                    mPresenter.confirmOrder(orderKey, "", marks, pay_type, "0", "", address_id, "false", leftName, rightName, delivery_method, logistics_type, order_express_type);
                } else if (from.equals("routine")) {
                    mPresenter.toPay(from, pay_type, orderKey);
                }
                btPay.setEnabled(true);
                break;
        }

    }

    Intent intent;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        if (IS_FORM){
//                            IS_FORM=false;
//                        }
                        intent = new Intent(mContext, MainActivity.class);
                        intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
                        intent.putExtra("from", "pay");
                        startActivity(intent);
                        break;
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        if (IS_FORM){
//                            IS_FORM=false;
//                            finish();
//                        }else {
                        intent = new Intent(mContext, MainActivity.class);
                        intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
                        intent.putExtra("from", "pay_cancel");
                        startActivity(intent);
//                        }

                    }

                    break;
                }

                default:
                    break;
            }
        }

        ;
    };
}
